package com.yunfeng.supercall.fragment;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.lin.activity.AddFriendActivity;
import com.lin.activity.EntrepriseDynamicActivity;
import com.lin.activity.FriendsShareWallActivity;
import com.lin.views.CustomPopupWindow;
import com.ly.quickdev.library.adapter.ListBaseAdapter.ViewHolder;
import com.ly.quickdev.library.fragment.DevBaseListFragment;
import com.yunfeng.supercall.R;
import com.yunfeng.supercall.activity.AddSuperFriendsActivity;
import com.yunfeng.supercall.activity.ChatActivity;
import com.yunfeng.supercall.activity.FriendShareListActivity;
import com.yunfeng.supercall.activity.SearchUserActivity;
import com.yunfeng.supercall.bean.AdsBean;
import com.yunfeng.supercall.bean.ChatMessageBean;
import com.yunfeng.supercall.bean.Constants;
import com.yunfeng.supercall.bean.ContactsBaseBean;
import com.yunfeng.supercall.bean.SuperFriendsBean;
import com.yunfeng.supercall.bean.SystemContactsBean;
import com.yunfeng.supercall.iface.MessageAccessable;
import com.yunfeng.supercall.manager.AdsManager;
import com.yunfeng.supercall.manager.ChatMessageManager;
import com.yunfeng.supercall.manager.ManagerFactory;
import com.yunfeng.supercall.manager.SuperFriendsManager;

public class CopyOfRecentChatListFragment extends DevBaseListFragment<ContactsBaseBean>
implements Constants, MessageAccessable {

	ChatMessageManager mChatMessageManager;
	List<SuperFriendsBean> mAllContactors;
	public static final String PATTERN = "yyyy-MM-dd HH:mm";

	public static final String PATTERN1 = "HH:mm";
	private SimpleDateFormat mDateFormat;
	CustomPopupWindow pw;
	View mView;
	private UpdateBroadcastReceiver mUpdateBroadcastReceiver;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		mView = inflater.inflate(R.layout.fragment_recent_chat_list, null);
		pw = new CustomPopupWindow(getActivity());
		FrameLayout  mFrameLayoutMore = (FrameLayout) mView.findViewById(R.id.framelayout_more);
		mFrameLayoutMore.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				pw.show();
			}
		});

		FrameLayout mFrameLayoutSearch = (FrameLayout) mView.findViewById(R.id.framelayout_search);
		mFrameLayoutSearch.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(new Intent(getActivity(), AddFriendActivity.class));
			}
		});

		IntentFilter filter = new IntentFilter();
		filter.addAction(ACTION_RECEIVE_MSG);
		mUpdateBroadcastReceiver = new UpdateBroadcastReceiver();
		getActivity().registerReceiver(mUpdateBroadcastReceiver, filter);
		
		IntentFilter filter2 = new IntentFilter();
		filter2.addAction(ACTION_RECEIVE_MSG2);
		mUpdateBroadcastReceiver2 = new UpdateBroadcastReceiver2();
		getActivity().registerReceiver(mUpdateBroadcastReceiver2, filter2);
		return mView;
	}



	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if(mUpdateBroadcastReceiver != null) {
			getActivity().unregisterReceiver(mUpdateBroadcastReceiver);
			mUpdateBroadcastReceiver = null;
		}
		if(mUpdateBroadcastReceiver2 != null) {
			getActivity().unregisterReceiver(mUpdateBroadcastReceiver2);
			mUpdateBroadcastReceiver2 = null;
		}

	}



	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mChatMessageManager = ChatMessageManager.getInstance(getActivity());
		mList = new ArrayList<ContactsBaseBean>();
		mDateFormat = new SimpleDateFormat(PATTERN);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
//		AdsManager mAdsManager = (AdsManager) ManagerFactory
//				.createManager(AdsBean.class);
//		mAdsManager.addAdsHeader(mListView.getRefreshableView(), 0);
		super.onActivityCreated(savedInstanceState);

		setEmptyMessage(getString(R.string.no_chat));
		View search = findViewById(R.id.search_area);
		if (search != null) {
			search.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					startActivity(new Intent(getActivity(),
							SearchUserActivity.class));
				}
			});
		}
		View add = findViewById(R.id.add_friends_area);
		if (add != null) {
			add.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					startActivity(new Intent(getActivity(),
							AddSuperFriendsActivity.class));
				}
			});
		}

	}

	@Override
	public Mode getRefreshMode() {
		return Mode.DISABLED;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (convertView == null) {
			if (position == 0) {
				convertView = getActivity().getLayoutInflater().inflate(
						R.layout.list_item_system_friends, null);
				
			} else {
				convertView = getActivity().getLayoutInflater().inflate(
						R.layout.list_item_recent_chating, null);
			}

		}
		ContactsBaseBean base = mList.get(position);

		ContactsBaseBean.setupSingleLineContactsView(convertView, base);
		if (base instanceof SuperFriendsBean) {
			final TextView red = ViewHolder.get(convertView, R.id.red_dot);
			final TextView content = ViewHolder.get(convertView, R.id.content);
			final TextView date = ViewHolder.get(convertView, R.id.date);
			
			List<ChatMessageBean> chatMessages = mChatMessageManager
					.findChatMessages(base);
			/*List<ChatMessageBean> chatMessages = mChatMessageManager.findAllChatMessages();*/
			 red.setVisibility(base.isUnread() ? View.VISIBLE : View.GONE);
			red.setVisibility(View.VISIBLE);
			int count = base.getUnreadCount();
			red.setVisibility(count == 0 ? View.INVISIBLE : View.VISIBLE);
			red.setText(base.getUnreadCount() + "");
			int size = chatMessages.size();
			if (size > 0) {
				ChatMessageBean message = chatMessages.get(size - 1);
				String text = "";
				switch (message.getChatType()) {
				case ChatMessageBean.TYPE_PIC:
					text = "[图片]";
					break;
				case ChatMessageBean.TYPE_VOICE:
					text = "[语音]";
					break;
				case ChatMessageBean.TYPE_LOCATION:
					text = "[位置]";
					break;
				default:
					text = message.getContent();
					break;
				}

				if (date != null) {
					SimpleDateFormat dateFormat = new SimpleDateFormat(PATTERN1);
					Calendar now = Calendar.getInstance();
					Calendar calendar = Calendar.getInstance();
					calendar.setTimeInMillis(message.getReceiveTime());
					int i = now.get(Calendar.DAY_OF_YEAR);
					int j = calendar.get(Calendar.DAY_OF_YEAR);
					if (i == j) {
						date.setText(dateFormat.format(new Date(message
								.getReceiveTime())));
					} else if (i - j == 2) {
						date.setText("前天："
								+ dateFormat.format(new Date(message
										.getReceiveTime())));
					} else if (i - j == 1) {
						date.setText("昨天："
								+ dateFormat.format(new Date(message
										.getReceiveTime())));
					} else {
						date.setText(mDateFormat.format(new Date(message
								.getReceiveTime())));
					}

				}
				if (content != null) {
					content.setText(text);
				}
			}
		}
		return convertView;
	}

	@Override
	public int getItemViewType(int position) {
		if (position == 0) {
			return 0;
		}
		return 1;
	}

	@Override
	public int getViewTypeCount() {
		return 2;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
	}

	@Override
	public void onResume() {
		super.onResume();
		load();
	}
	
	ArrayList<ChatMessageBean> mListChatMessageBean = new ArrayList<ChatMessageBean>();
	private UpdateBroadcastReceiver2 mUpdateBroadcastReceiver2; 

	public void load() {
		if (mList == null) {
			mList = new ArrayList<ContactsBaseBean>();
		}
		mList.clear();
		SystemContactsBean mContacts = new SystemContactsBean();
		mContacts.setImgId(R.drawable.ic_chat_company);
		mContacts.setReal_name("企业动态");
		mList.add(mContacts);
		mAllContactors = (List<SuperFriendsBean>) ((SuperFriendsManager) ManagerFactory
				.createManager(SuperFriendsBean.class)).getListInCache();
		List<ContactsBaseBean> temp = new ArrayList<ContactsBaseBean>();
		for (ContactsBaseBean c : mAllContactors) {
			List<ChatMessageBean> messages = mChatMessageManager
					.findChatMessages(c);
			if (messages != null && !messages.isEmpty()) {
				temp.add(c);
				c.setLastChatTime(messages.get(messages.size() - 1)
						.getReceiveTime());
			}
		}
		Collections.sort(temp, new Comparator<ContactsBaseBean>() {

			@Override
			public int compare(ContactsBaseBean lhs, ContactsBaseBean rhs) {
				return (int) (rhs.getLastChatTime() - lhs.getLastChatTime());
			}
		});
		mList.addAll(temp);
		setListAdapter();
	}

	@Override
	public void loadData() {
		// make this call empty,no need here
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		ContactsBaseBean mBase = getItem(position);
		if (mBase instanceof SystemContactsBean) {

			/*startActivity(new Intent(getActivity(),
					FriendShareListActivity.class).putExtra(Constants.KEY_DATA,
					-3));*/
			startActivity(new Intent(getActivity(),
					EntrepriseDynamicActivity.class));

			//			startActivity(new Intent(getActivity(), FriendsShareWallActivity.class));
		} else {
			mBase.setUnread(false);
			mBase.setUnreadCount(0);
			startActivity(new Intent(getActivity(), ChatActivity.class)
			.putExtra(Constants.KEY_DATA, mBase));
		}
	}

	@Override
	public void refreshMessage() {
		load();
	}

	class UpdateBroadcastReceiver extends BroadcastReceiver {

		public UpdateBroadcastReceiver() {

		}

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			load();
		}

	}
	
	class UpdateBroadcastReceiver2 extends BroadcastReceiver {

		public UpdateBroadcastReceiver2() {

		}

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			load();
		}

	}
}
